<template>
  <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <el-alert
                title="只能为第三级分类设定参数"
                type="warning"
                show-icon
                :closable="false">
            </el-alert>
            选择商品分类：
            <el-cascader
                style="padding-top: 8px; width: 20em;"
                v-model="selectedCatId"
                clearable
                expandTrigger="hover"
                :options="cateList"
                :props="{ value: 'cat_id', label: 'cat_name',emitPath:false}"
                @change="catChange">
            </el-cascader>
            <el-tabs v-model="activeTab">
                <el-tab-pane label="动态参数" name="many">
                    <el-row>
                        <el-button type="primary" :disabled="selectedCatId==null" @click="showAddDialog">添加参数</el-button>
                    </el-row>
                    <el-table :data="paramList" row-key="attr_id" border stripe>
                        <el-table-column type="expand">
                            <template scope="scope">
                                <el-tag closable @close="attrRemove(scope.row,val)" type="success" 
                                    v-for="(val,index) in scope.row.attr_vals" :key="index">{{val}}</el-tag>
                                <!-- <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input> 
                                <el-button v-else class="button-new-tag" size="small" @click="handleInputVisible(scope.row)">新增</el-button> -->
                                <el-button class="button-new-tag" size="small" @click="showAddAttrDialog(scope.row)">新增</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="#" type="index"></el-table-column>
                        <el-table-column label="名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="success" icon="el-icon-edit"  @click="showEditDialog(scope.row)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="remove(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-row>
                        <el-button type="primary" :disabled="selectedCatId==null" @click="showAddDialog">添加属性</el-button>
                    </el-row>
                    <el-table :data="paramList2" row-key="attr_id" border stripe>>
                        <el-table-column type="expand">
                            <template scope="scope">
                                <el-tag closable @close="attrRemove(scope.row,val)" type="success" 
                                    v-for="(val,index) in scope.row.attr_vals" :key="index">{{val}}</el-tag>
                                <!-- <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="handleInputVisible(scope.row)">新增</el-button> -->
                                <el-button class="button-new-tag" size="small" @click="showAddAttrDialog(scope.row)">新增</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="#" type="index"></el-table-column>
                        <el-table-column label="名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="success" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="remove(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 新增参数对话框 -->
         <el-dialog title="添加参数" :visible.sync="addDialogVisible" width="50%" 
            :close-on-click-modal="false" >
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="80px">
                <el-form-item label="参数名称" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="add">确 定</el-button>
            </div>
      </el-dialog>
      <!-- 编辑参数对话框 -->
         <el-dialog title="编辑参数" :visible.sync="editDialogVisible" width="50%" 
            :close-on-click-modal="false" >
            <el-form ref="editFormRef" :model="editForm" :rules="addFormRules" label-width="80px">
                <el-form-item label="参数名称" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="edit">确 定</el-button>
            </div>
      </el-dialog>
  </div>
</template>

<script>
export default {
    data() {
        return {
            cateList: [],
            selectedCatId: null,
            activeTab: 'many',
            paramList: [],
            paramList2: [],
            addForm: {
                attr_name: '',
                attr_sel: 'many'
            },
            addDialogVisible: false,
            addFormRules: {
                attr_name: [
                   { required: true, message: '请输入名称', trigger: 'blur' }
                ]
            },
            editForm: {
                attr_name: '',
                attr_sel: '',
                attr_vals: []
            },
            editDialogVisible: false
        }
    },
    created() {
        this.getCatList();
    },
    methods: {
        async getCatList() {
            const { data: res} = await this.$http.get('categories');
            if(res.meta.status!=200) {
                return this.$message.error('获取商品分类失败！'+res.meta.msg);
            }
            this.cateList=res.data;
            console.log('cates',res.data);
        },
        async getParamList(sel) {
            if(!sel) sel=this.activeTab;
            const { data: res} = await this.$http.get('categories/'+this.selectedCatId+'/attributes',
                {params: {sel: sel}});
            if(res.meta.status!=200) {
                return this.$message.error('获取分类参数失败！'+res.meta.msg);
            }
            res.data.forEach(param=>{
                if(param.attr_vals) {
                    param.attr_vals=param.attr_vals.split(',');
                }
                else
                    param.attr_vals=[];
                // param.inputValue='';
                // param.inputVisible=false;
            });
            if(sel=='many')
                this.paramList=res.data;
            else
                this.paramList2=res.data;
            console.log('params',sel,res.data);
        },
        catChange(id) {
            if(id)
            {
                this.getParamList('many');
                this.getParamList('only');
            }
            else
            {
                this.paramList=[];
                this.paramList2=[];
            }
        },
        showAddDialog() {
            this.addForm.attr_name='';
            this.addForm.attr_sel=this.activeTab;

            this.addDialogVisible=true;
        },
        add() {
            this.$refs.addFormRef.validate(async (valid)=>{
                const { data: res} = await this.$http.post('categories/'+this.selectedCatId+'/attributes',
                this.addForm);
                if(res.meta.status!=201) {
                    return this.$message.error('添加分类参数失败！'+res.meta.msg);
                }
                this.addDialogVisible=false;
                this.getParamList();
                this.$message.success('添加分类参数成功！');
            });
        },
        async remove(param) {
            const confirm= await this.$confirm('确定删除吗？','确认')
                .catch(err=>err);
            if(confirm=='confirm') {
                  const { data: res} = await this.$http.delete('categories/'+this.selectedCatId+'/attributes/'+param.attr_id);
                  if(res.meta.status!=200) {
                    return this.$message.error('删除分类参数失败！'+res.meta.msg);
                }
                this.getParamList();
                this.$message.success('删除分类参数成功！');
            }
        },
        showEditDialog(param) {
            this.editForm.attr_id=param.attr_id;
            this.editForm.attr_name=param.attr_name;
            this.editForm.attr_sel=param.attr_sel;
            this.editForm.attr_vals=param.attr_vals.join(',');
            this.editDialogVisible=true;
        },
        edit() {
            this.$refs.editFormRef.validate(async (valid)=>{
                const { data: res} = await this.$http.put(
                    'categories/'+this.selectedCatId+'/attributes/'+this.editForm.attr_id,
                    this.editForm);
                if(res.meta.status!=200) {
                    return this.$message.error('修改分类参数失败！'+res.meta.msg);
                }
                this.editDialogVisible=false;
                this.getParamList();
                this.$message.success('修改分类参数成功！');
            });
        },
        strToArray(str) {
            if(str) return str.split(',');
            return [];
        },
        async attrRemove(param,val) {
            this.editForm.attr_id=param.attr_id;
            this.editForm.attr_name=param.attr_name;
            this.editForm.attr_sel=param.attr_sel;
            var vals=[];
            param.attr_vals.forEach(v=>{if(v!=val) vals.push(v)});
            console.log('attrRemove',vals);
            this.editForm.attr_vals=vals.join(',');           
            const { data: res} = await this.$http.put(
                    'categories/'+this.selectedCatId+'/attributes/'+this.editForm.attr_id,
                    this.editForm);
            if(res.meta.status!=200) {
                return this.$message.error('修改分类参数失败！'+res.meta.msg);
            }
            param.attr_vals=vals;
            //this.getParamList();
        },
        // handleInputVisible(param) {
        //     param.inputVisible=true;
        //     //param.inputValue='';
        //     // this.$nextTick(_=>{
        //     //     console.log('refs',this.$refs.saveTagInput);
        //     //     this.$refs.saveTagInput.$refs.input.focus();
        //     // });
        //     await this.$nextTick();
        //     this.$refs.saveTagInput.$refs.input.focus();
        // },
        // async handleInputConfirm(param) {
        //     console.log('handleInputConfirm',this);
        //     var input=param.inputValue.trim();
        //     if(input)
        //     {
        //         this.editForm.attr_id=param.attr_id;
        //         this.editForm.attr_name=param.attr_name;
        //         this.editForm.attr_sel=param.attr_sel;
        //         var vals=param.attr_vals.concat([param.inputValue]);
        //         console.log('attrAdd',vals);
        //         this.editForm.attr_vals=vals.join(',');           
        //         const { data: res} = await this.$http.put(
        //                 'categories/'+this.selectedCatId+'/attributes/'+this.editForm.attr_id,
        //                 this.editForm);
        //         if(res.meta.status!=200) {
        //             return this.$message.error('修改分类参数失败！'+res.meta.msg);
        //         }
        //         param.attr_vals=vals;
        //         param.inputValue='';
        //     }
        //     param.inputVisible=false;
        // },
        async showAddAttrDialog(param) {
            const prompt = await this.$prompt('请输入参数或属性名称',{
                inputPattern:/.+/,
                inputErrorMessage:'请输入名称'
            }).catch(err=>err);
            // console.log('showAddAttrDialog',prompt);
            if(prompt.action=='confirm') {
                this.editForm.attr_id=param.attr_id;
                this.editForm.attr_name=param.attr_name;
                this.editForm.attr_sel=param.attr_sel;
                var vals=param.attr_vals.concat([prompt.value]);
                console.log('attrAdd',vals);
                this.editForm.attr_vals=vals.join(',');           
                const { data: res} = await this.$http.put(
                        'categories/'+this.selectedCatId+'/attributes/'+this.editForm.attr_id,
                        this.editForm);
                if(res.meta.status!=200) {
                    return this.$message.error('修改分类参数失败！'+res.meta.msg);
                }
                param.attr_vals=vals;
            }
        }
    }
}
</script>

<style lang="less" scoped>
.el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 120px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>